import fetch from 'isomorphic-fetch';
import cookie from 'js-cookie';
import reqwest from 'reqwest';

// const remoteUrl = 'http://oa.toprivermis.com:85';
const remoteUrl = 'http://127.0.0.1:8088/api';
// const remoteUrl = '';
import {message} from 'antd';

const errorMessages = (res) => `${res.status} ${res.statusText}`;

function check401(res) {
  if (res.status === 401) {
    location.href = '/401';
  }
  return res;
}

function check404(res) {
  if (res.status === 404) {
    return Promise.reject(errorMessages(res));
  }
  return res;
}

function jsonParse(res) {
  return res.json().then(jsonResult => ({ ...res, jsonResult }));
}

function errorMessageParse(res) {
  const {message } = res.jsonResult;
  if (message.returnCode === 1) {
     return Promise.reject(message.returnCode);
  }
  return Promise.resolve(res.jsonResult);
}

function xFetch(url, options) {
  const opts = { ...options };
  opts.headers = {
    ...opts.headers,
    'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'
  };
  // try{
  //     return fetch(remoteUrl+url, opts)
  //     .then(check401)
  //     .then(check404)
  //     .then(jsonParse)
  //     .then(errorMessageParse);
  //   }catch(e){
  //     return reqwest({
  //       url: remoteUrl+url,
  //       method: opts.method,
  //       contentType:opts.headers['Content-Type'],
  //       data: opts.body,
  //       type: 'json',
  //       ...opts
  //     })
  //     .then(function(resp){
  //       return resp;
  //     })
  //   }
    return reqwest({
      url: remoteUrl+url,
      // url: url,
      method: opts.method,
      contentType:opts.headers['Content-Type'],
      data: opts.body,
      type: 'json',
      withCredentials: true,
      ...opts
    })
    .then(function(resp){
      return resp;
    })

}

export default xFetch;
